package no.ffi.gismoidm.certstore;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import javax.security.auth.x500.X500Principal;
import no.ffi.gismoidm.idp.Config;
import no.ffi.tpm.crypto.CryptoOperations;
import no.ffi.tpm.crypto.CryptoOperationsFactory;

/**
 *
 * @author anders
 */
public class WebStorageService implements CertificateService {

    X509Certificate trustAnchor;
    String serviceURL;

    WebStorageService(X509Certificate trustAnchor) {
        Config.loadPropertiesFrom(null);
        this.trustAnchor = trustAnchor;
        serviceURL = Config.getProperty("IDP_CA_SERVICE_POINT");
        //this.serviceURL = serviceURL; Take from Config
    }

    @Override
    public X509Certificate retrieveAndValidate(X500Principal dn) throws Exception {
        String param = "subj_cert_dn=" + URLEncoder.encode(dn.getName(), "UTF-8");
        return getHTTP(serviceURL, param);
    }

    @Override
    public X509Certificate retrieveAndValidate(String subjectHash, String serialNumber) throws Exception {
        String param = "subj_cert_hash=" + subjectHash + ":" + serialNumber;
        return getHTTP(serviceURL, param);
    }

    private static X509Certificate getHTTP(String url, String param) throws Exception {
        URL serviceUrl = new URL(url + "?" + param);
        HttpURLConnection urlc = (HttpURLConnection) serviceUrl.openConnection();

        urlc.setRequestMethod("GET");
        urlc.setDoInput(true);
        // Now wait for response
        // Error/timeout conditions throws a SocketException
        InputStream is = urlc.getInputStream();
        return CertificateFileOperations.loadDERCert(is);
    }

    public static void main(String[] args) throws Exception {
        String dn = "CN=Edward Fongen,O=Forsvarets Forskningsinstitutt,C=NO";
        CryptoOperations crOp = CryptoOperationsFactory.getInstance("JCE");
        X509Certificate trustAnchor = crOp.getTrustAnchorCert();
        WebStorageService wss = new WebStorageService(trustAnchor);

        X509Certificate cert = wss.retrieveAndValidate(new X500Principal(dn));
        cert = wss.retrieveAndValidate("cea7c891", "17478804521253778975");
        System.out.println(cert);
    }

    public static void mainx(String[] args) throws Exception {
        X509Certificate rootCert = CertificateFileOperations.loadAnyCert("/home/anders/tech/idm-coi/easyCA-IdM-mil-dep/certs/cacert.pem");
        X509Certificate edward = CertificateFileOperations.loadAnyCert("/home/anders/tech/idm-coi/easyCA-IdM-mil-dep/certs/573f2c84.0");
        X509Certificate aik = CertificateFileOperations.loadAnyCert("/home/anders/tech/idm-coi/easyCA-IdM-mil-dep/certs/cea7c891.0");

        edward.verify(rootCert.getPublicKey());
        aik.verify(rootCert.getPublicKey());
    }
}
